package tcdx.uap.controller;

import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import tcdx.uap.common.entity.AjaxResult;
import tcdx.uap.common.entity.page.TableDataInfo;
import tcdx.uap.common.utils.Lutils;
import tcdx.uap.common.utils.MapUtils;
import tcdx.uap.common.utils.SqlUtil;
import tcdx.uap.common.utils.StringUtils;
import tcdx.uap.mapper.BaseDBMapper;
import tcdx.uap.mapper.FlowableMapper;
import tcdx.uap.service.BaseDBService;
import tcdx.uap.service.FlowableService;
import tcdx.uap.service.entities.UserAction;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/uap/flowable")
public class FLowableController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(FLowableController.class);
    private String prefix = "";

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private FlowableMapper flowableMapper;

    @Autowired
    private BaseDBService baseDBService;

    /**
     * 查询运已经部署的流程定义
     * @param
     * @return
     * @throws
     *
     */
//    @RequiresPermissions("system:flowable:get_deploy_list")
    @PostMapping("/get_deploy_list")
    @ResponseBody
    public TableDataInfo get_deploy_list()
    {
        PageHelper.startPage(1, 10, null).setReasonable(true);
        List list= flowableMapper.select_flowable_act_re_deployment_pagedata();
        return getDataTable(list);
    }

    /**
     * 部署流程
     * @param map Map<String, Object>,ajax传入的参数,包含:flow_text
     * @return AjaxResult
//    @RequiresPermissions("system:flowable:deploy_flow")
    @PostMapping("/deploy_flow")
    @ResponseBody
    public AjaxResult deploy_flow(@RequestBody Map<String, Object> map)
    {
        System.out.println("接受到的模型：");
        System.out.println(map);
        Object menu_id = map.get("menu_id");
        String old_proc_def_id_=(String) map.get("proc_def_id_");
        String new_deployment_id_=flowableService.deploy_flow(Math.random()+".bpmn20.xml",map.get("flow_text").toString());
        //获得proc_def_id_
        Map procdef = baseDBService.selectEq("act_re_procdef",Lutils.genList("id_"), MapUtils.G("deployment_id_",new_deployment_id_)).get(0);
        String new_proc_def_id_ =procdef.get("id_").toString();
        //更新v_datatable
        int rs = baseDBService.updateEq("v_datatable",
                MapUtils.G("proc_def_id_", new_proc_def_id_, "deployment_id_", new_deployment_id_, "deployment_time_",new Date()),
                MapUtils.G("menu_id",map.get("menu_id")) );
        //获取保存后的最新数据
        Map datatable = baseDBService.selectEq("v_datatable", MapUtils.G("menu_id",menu_id)).get(0);
        //记录部署日志
        rs = baseDBService.insertMap("v_datatable_log", datatable);

        //更新flowable关键表
        baseDBService.updateEq("act_ru_actinst",MapUtils.G("proc_def_id_", new_proc_def_id_),
                MapUtils.G("proc_def_id_", old_proc_def_id_));
        baseDBService.updateEq("act_ru_execution",MapUtils.G("proc_def_id_", new_proc_def_id_),
                MapUtils.G("proc_def_id_", old_proc_def_id_));
        baseDBService.updateEq("act_ru_task",MapUtils.G("proc_def_id_", new_proc_def_id_),
                MapUtils.G("proc_def_id_", old_proc_def_id_));
        baseDBService.updateEq("act_hi_actinst",MapUtils.G("proc_def_id_", new_proc_def_id_),
                MapUtils.G("proc_def_id_", old_proc_def_id_));
        baseDBService.updateEq( "act_hi_procinst",MapUtils.G("proc_def_id_", new_proc_def_id_),
                MapUtils.G("proc_def_id_", old_proc_def_id_));
        baseDBService.updateEq("act_hi_taskinst",MapUtils.G("proc_def_id_", new_proc_def_id_),
                MapUtils.G("proc_def_id_", old_proc_def_id_));
        //更新新prodefid
//        baseDBService.updateEq( datatable.get("table_name").toString(),MapUtils.G("proc_def_id_", new_proc_def_id_),
//                MapUtils.G("proc_def_id_", old_proc_def_id_));
//        baseDBService.updateEq(datatable.get("table_name")+"_log",MapUtils.G("proc_def_id_",procdef.get("id_")),
//                MapUtils.G("proc_def_id_", old_proc_def_id_));
        // 获取BpmnModel
//        BpmnModel bpmnModel = repositoryService.getBpmnModel(new_proc_def_id_);
//        // 获取所有的UserTask
//        List<StartEvent> startEvents = bpmnModel.getMainProcess().getFlowElements().stream()
//                .filter(flowElement -> flowElement instanceof StartEvent)
//                .map(flowElement -> (StartEvent) flowElement)
//                .collect(Collectors.toList());
//        // 获取所有的UserTask
//        List<EndEvent> endEvents = bpmnModel.getMainProcess().getFlowElements().stream()
//                .filter(flowElement -> flowElement instanceof EndEvent)
//                .map(flowElement -> (EndEvent) flowElement)
//                .collect(Collectors.toList());
//        // 获取所有的UserTask
//        List<UserTask> userTasks = bpmnModel.getMainProcess().getFlowElements().stream()
//                .filter(flowElement -> flowElement instanceof UserTask)
//                .map(flowElement -> (UserTask) flowElement)
//                .collect(Collectors.toList());
//        baseDBService.deleteEq("v_flow_activities", Lutils.genMap("menu_id", menu_id));
//        // StartEvent
//        for (StartEvent startEvent : startEvents) {
//            baseDBService.insertMap("v_flow_activities", Lutils.genMap("menu_id",menu_id, "type","bpmn:UserTask","act_id", startEvent.getId(), "name", startEvent.getName()==null?"开始":startEvent.getName()));
//        }
//        // EndEvent
//        for (EndEvent endEvent : endEvents) {
//            baseDBService.insertMap("v_flow_activities", Lutils.genMap("menu_id",menu_id, "type","bpmn:UserTask","act_id", endEvent.getId(), "name", endEvent.getName()==null?"结束":endEvent.getName()));
//        }
//        // 遍历UserTask
//        for (UserTask userTask : userTasks) {
//            baseDBService.insertMap("v_flow_activities", Lutils.genMap("menu_id",menu_id, "type","bpmn:UserTask","act_id", userTask.getId(), "name", userTask.getName()));
//        }
        return AjaxResult.success("suc", datatable);
    }

     */

    /***
     * 查根据 flow_def_id 获取流程定义的XML和名称
     * @param map ，包含flow_def_id
     * @return 返回XMl文本
     * **/
////    @RequiresPermissions("system:flowable:get_deployment_info")
//    @PostMapping("/get_deployment_info")
//    @ResponseBody
//    public AjaxResult get_deployment_info(@RequestBody Map<String, Object> map)
//    {
//        System.out.println("接受到的模型：");
//        System.out.println(map);
//        String proc_def_id = map.get("proc_def_id_").toString();
//        String deployment_id = map.get("deployment_id_").toString();
//        //xml数据
//        String xml= flowableService.get_deployment_xml_by_id(proc_def_id);
//        //流程部署信息
//        Map<String,Object> deployInfo = flowableService.get_deployment(deployment_id);
//        //用户任务表单信息
//        List<Map> userTaskFormList = baseDBService.selectEq("v_flow_usertask_form", MapUtils.G("proc_def_id_",  proc_def_id) );
//        Map<String,Object> re = MapUtils.Combine(deployInfo,
//                MapUtils.G("xml", xml, "usertaskForms", userTaskFormList)
//        );
//        return AjaxResult.success("success", re);
//    }

    /**
     * 删除流程定义部署
     * */
//    @RequiresPermissions("system:flowable:delete_deployment")
//    @PostMapping("/delete_deployment")
//    @ResponseBody
//    public AjaxResult delete_deployment(@RequestBody Map<String, Object> map)
//    {
//        int rs = flowableService.delete_deployment(map.get("deployment_id_").toString());
//        return AjaxResult.success(rs);
//    }

    /**
     * 获取流程usertask的表单,不带数据.用于获取start的表单
     * */
//    @RequiresPermissions("system:flowable:get_usertask_form_withoutdata")
    @PostMapping("/get_usertask_form_withoutdata")
    @ResponseBody
    public AjaxResult get_usertask_form_withoutdata(@RequestBody Map<String, Object> map)
    {
        String proc_def_id_=map.get("proc_def_id_").toString();
        String action_type=map.get("action_type").toString();
        //查询表单
        List<Map> formList = baseDBService.selectEq("v_flow_usertask_form", MapUtils.G("proc_def_id_",  proc_def_id_,"action_type",  action_type));
        //获取表单字段配置
        List<Map> reformItems = null;
        if(formList.size()>0){
            reformItems = baseDBService.selectEq("v_form_field",MapUtils.G("form_id",  formList.get(0).get("form_id")));
        }
        return AjaxResult.success("suc", MapUtils.Combine(
                MapUtils.New("formItems", reformItems)
        ));
    }

    /**
     * 获取流程usertask的表单,带当前最新数据
     * */
//    @RequiresPermissions("system:flowable:get_usertask_form_withdata")
    @PostMapping("/get_usertask_form_withdata")
    @ResponseBody
    public AjaxResult get_usertask_form_withdata(@RequestBody Map<String, Object> map)
    {
        String proc_def_id_=map.get("proc_def_id_").toString();
        String proc_inst_id_=map.get("proc_inst_id_").toString();
        String task_def_key_=map.get("task_def_key_").toString();
        String action_type=map.get("action_type").toString();
        Object data_id = map.get("data_id");
        //查询表单
        List<Map> formList = baseDBService.selectEq("v_flow_usertask_form",MapUtils.G("proc_def_id_",  proc_def_id_,
                "task_def_key_",  task_def_key_,"action_type",  action_type));
        //获取表单字段配置
        List<Map> reformItems = null;
        List<Map> reformData = null;
        if(formList.size()>0){
            reformItems = baseDBService.selectEq("v_form_field", MapUtils.G("form_id",  formList.get(0).get("form_id")));
            reformData = baseDBService.selectEq("v_usertask_data01", MapUtils.G("id",  data_id));
        }
        return AjaxResult.success("suc", MapUtils.Combine(
                MapUtils.New("formItems", reformItems),
                MapUtils.New("formData", reformData)
        ));
    }

    @Autowired
    BaseDBMapper baseDBMapper;
    /**
     * 增加列定义
     * */
    //@RequiresPermissions("system:flowable:add_flow_tbl_col")
    @PostMapping("/add_flow_tbl_col")
    @ResponseBody
    public AjaxResult add_flow_tbl_col(@RequestBody Map<String, Object> map)
    {
        System.out.println(map);
        Object table_id = map.get("table_id");
        String columnChineseName = ((Map)map.get("insertMap")).get("label_title").toString();
        String columnName = StringUtils.chnToPinyin(columnChineseName);
        ((Map)map.get("insertMap")).put("field", columnName);
        String columnType = ((Map)map.get("insertMap")).get("db_field_type").toString();
        Integer columnCharLength = (Integer)((Map)map.get("insertMap")).get("db_field_varchar_length");
        Integer columnNumberPrecision = (Integer)((Map)map.get("insertMap")).get("db_field_numeric_precision");
        SqlUtil.filterKeyword(columnName);
        //获取流程关联的表名
        List<Map> tbl_data = baseDBService.selectEq("v_datatable",MapUtils.G("id",  table_id));
        String tn = tbl_data.get(0).get("table_name").toString();
        //将字段类型转换为数据库可识别的类型
        columnType = get_db_type(columnType, columnCharLength, columnNumberPrecision);
        String msg="";
        int rs = 0;
        try {
            //增加表结构的列
            baseDBMapper.tableAddColumn(MapUtils.G("tn", tn,"columnName", columnName,"columnType", columnType));
            //包括日志表
            baseDBMapper.tableAddColumn(MapUtils.G("tn", tn+"_log","columnName", columnName,"columnType", columnType));

            //增加表结构的列
            rs = baseDBMapper.insertMap(MapUtils.G("tn", "v_datatable_columns","insertMap", map.get("insertMap")));
            msg = "操作成功";
        }
        catch(Exception e){
            e.printStackTrace();
            msg = e.getMessage();
        }
        return AjaxResult.success(msg);
    }

    public String get_db_type(String db_field_type,Integer length, Integer prec){
        //将字段类型转换为数据库可识别的类型
        if(db_field_type.equals("文本"))
            return "varchar("+length+")";
        else if(db_field_type.equals("数字"))
            return "NUMERIC(16, "+prec+")";
        else if(db_field_type.equals("时间")||db_field_type.equals("日期"))
            return "timestamp";
        else
            return "varchar(1000)";
    }
    /**
     * 修改列定义
     * */
    //@RequiresPermissions("system:flowable:edit_flow_tbl_col")
    @PostMapping("/edit_flow_tbl_col")
    @ResponseBody
    public AjaxResult edit_flow_tbl_col(@RequestBody Map<String, Object> map)
    {
        System.out.println(map);
        Object table_id = map.get("table_id");
        String newColumnChName = ((Map)map.get("updateMap")).get("label_title").toString();
        String newColumnName = StringUtils.chnToPinyin(newColumnChName);
        ((Map)((Map<?, ?>) map.get("updateMap"))).put("field", newColumnName);
        String newColumnType = ((Map)map.get("updateMap")).get("db_field_type").toString();
        Integer columnCharLength = (Integer)((Map)map.get("updateMap")).get("db_field_varchar_length");
        Integer columnNumberPrecision = (Integer)((Map)map.get("updateMap")).get("db_field_numeric_precision");
        SqlUtil.filterKeyword(newColumnName);
        //获取流程关联的表名
        List<Map> tbl_data = baseDBService.selectEq("v_datatable", MapUtils.G("id",  table_id));
        String tn = tbl_data.get(0).get("table_name").toString();
        //获取修改字段的原数据
        List<Map> tbl_field_list = baseDBService.selectEq("v_datatable_columns",MapUtils.G("id",  map.get("id")));
        Map old_field = tbl_field_list.get(0);
        String oldColumnType = old_field.get("db_field_type").toString();
        oldColumnType = get_db_type(oldColumnType,(Integer)old_field.get("db_field_varchar_length"),(Integer)old_field.get("db_field_numeric_precision"));
        newColumnType = get_db_type(newColumnType, columnCharLength, columnNumberPrecision);
        String msg="";
        int rs = 0;
        try {
            //修改字段类型
            if(!oldColumnType.equals(newColumnType)) {
                baseDBMapper.tableAlterColumnType(MapUtils.Combine(MapUtils.New("tn", tn),
                        MapUtils.New("columnName", old_field.get("field")),
                        MapUtils.New("oldColumnType", oldColumnType),
                        MapUtils.New("newColumnType", newColumnType)));

                baseDBMapper.tableAlterColumnType(MapUtils.Combine(MapUtils.New("tn", tn + "_log"),
                        MapUtils.New("columnName", old_field.get("field")),
                        MapUtils.New("oldColumnType", oldColumnType),
                        MapUtils.New("newColumnType", newColumnType)));
            }
            //修改字段名称，发生变化才修改名称，否则会出错
            if(!newColumnName.equals(old_field.get("field").toString().trim())) {
                baseDBMapper.tableAlterColumnName(MapUtils.Combine(MapUtils.New("tn", tn),
                        MapUtils.New("columnName", old_field.get("field")),
                        MapUtils.New("newColumnName", newColumnName)
                ));
                baseDBMapper.tableAlterColumnName(MapUtils.Combine(MapUtils.New("tn", tn+"_log"),
                        MapUtils.New("columnName", old_field.get("field")),
                        MapUtils.New("newColumnName", newColumnName)
                ));
            }
            //修改数据表
            rs = baseDBService.updateEq("v_datatable_columns", (Map)map.get("updateMap"),MapUtils.G("id", map.get("id")));
            msg = "操作成功";
        }
        catch(Exception e){
            e.printStackTrace();
            msg = e.getMessage();
            return AjaxResult.error(msg);
        }
        return AjaxResult.success(msg);
    }


    /**
     * 删除列
     * */
    //    @RequiresPermissions("uap:base_db:drop_col")
    @PostMapping("/drop_flow_tbl_col")
    @ResponseBody
    public AjaxResult drop_col(@RequestBody Map<String, Object> map)
    {
        System.out.println(map);
        Object table_id = map.get("table_id");
        String columnName = map.get("columnName").toString();
        SqlUtil.filterKeyword(columnName);
        //获取流程关联的表名
        List<Map> tbl_data = baseDBService.selectEq("v_datatable",MapUtils.G("id",  table_id));
        String tn = tbl_data.get(0).get("table_name").toString();
        //执行删除动作
        String msg = "";
        int rs = -1;
        try {
            //删除表结构
            baseDBMapper.tableDropColumn(MapUtils.Combine(MapUtils.New("tn", tn), MapUtils.New("columnName", columnName)));
            //包括日志表
            baseDBMapper.tableDropColumn(MapUtils.Combine(MapUtils.New("tn", tn+"_log"), MapUtils.New("columnName", columnName)));
            //删除数据表
            rs = baseDBService.deleteEq("v_datatable_columns",MapUtils.G("table_id", table_id,"field", columnName));
            msg="操作成功";
        }catch(Exception e){
            e.printStackTrace();
            msg = e.getMessage();
        }
        return AjaxResult.success(msg);
    }

    /**
     * 创建基本表结构
     * */
    //    @RequiresPermissions("uap:flowable:create_datatable")
    @PostMapping("/create_datatable")
    @ResponseBody
    @Transactional
    public AjaxResult create_datatable(@RequestBody Map<String, Object> map) {
        //插入数据表信息
        List exist = baseDBService.selectEq("v_datatable", Lutils.genMap("table_display_name", map.get("table_display_name")));
        if(exist.size()>0){
            return AjaxResult.success("表名重复");
        }
        else{
            baseDBService.insertMap("v_datatable", Lutils.genMap("type", "data"));
            Map datatable = baseDBService.selectNewById("v_datatable").get(0);
            Integer datatable_id = (Integer)datatable.get("id");
            String table_name = "z_datatable" + datatable_id;
            baseDBService.updateEq("v_datatable", Lutils.genMap("table_name", table_name, "table_display_name", "数据表"+datatable_id), Lutils.genMap("id", datatable_id));
            datatable.put("table_name", table_name);
            datatable.put("table_display_name", "数据表"+datatable_id);
            String same_sql =
                    "task_id_ varchar(100),\n" +
                    "task_name_ varchar(100),\n" +
                    "task_def_key_ varchar(100),\n" +
                    "prev_deliver_ varchar(50),\n" +
                    "prev_deliver_group_ integer,\n" +
                    "prev_deliver_time_ timestamp ,\n" +
                    "prev_deliver_type_ varchar(20),\n" +
                    "prev_node_type_ varchar(100),\n" +
                    "prev_node_id_ varchar(100),\n" +
                    "prev_node_name_ varchar(100),\n" +
                    "receiver_ varchar(50),\n" +
                    "receiver_group_ integer,\n" +
                    "complete_user_ varchar(50),\n" +
                    "complete_group_ integer,\n" +
                    "complete_time_ timestamp,\n" +
                    "complete_type_ varchar(20),\n" +
                    "update_user_ varchar(20),\n" +
                    "update_group_ integer,\n" +
                    "update_time_ timestamp,\n" +
                    "update_type_ varchar(20),\n" +
                    "is_done_ boolean,\n" +
                    "time_if_delete_ timestamp,\n"+
                    "form_id_ int4\n";
            baseDBMapper.executeSql("create table "+table_name+" (\n" +
                    "id_ INT PRIMARY KEY DEFAULT nextval('v_datatable_id_seq'),\n" +
                    same_sql +
                    ")");
            baseDBMapper.executeSql("create table "+table_name+"_log (\n" +
                    "log_id_ serial primary key,\n" +
                    "log_time_ timestamp default CURRENT_TIMESTAMP,\n" +
                    "id_ integer,\n" +
                    same_sql +
                    ")");
            datatable.put("update_time", new Date());
            datatable.put("update_type", "create");
            baseDBService.insertMap("v_datatable_update_log", datatable);
            //插入功能信息
            return AjaxResult.success("操作成功", datatable);
        }
    }

    //@RequiresPermissions("uap:flowable:select_taskview_config")
    @PostMapping("/get_taskview_config")
    @ResponseBody
    public AjaxResult get_taskview_config(@RequestBody Map<String, Object> map) {
        Map re = new HashMap<String,Object>();
        //根据menu_id获取任务配置
        List<Map> table = baseDBService.selectEq("v_datatable", MapUtils.G("menu_id", map.get("menu_id")) );
        //根据menu_id获取任务配置
        List<Map> tableList = baseDBService.selectEq("v_task_tableview",
                MapUtils.G("id", map.get("tableview_id")),
                MapUtils.G("ord", "asc"));
        //获取表单form
        List formList = baseDBService.selectEq("v_form_field",
                MapUtils.G("form_id", tableList.get(0).get("search_form_id")),
                MapUtils.G("ord", "asc"));
        re.put("search_form_items", formList);
        //获取表单form旁的按钮
        List topBtnList = flowableMapper.select_task_top_btns(map);
        re.put("top_buttons", topBtnList);
        //获取表格列
        List<Map> tableColList = flowableMapper.get_taskview_col_cfg(Lutils.genMap("tableview_id", map.get("tableview_id"),"table_id", table.get(0).get("id")));
        //获取表格列按钮
        List<Map> tableColBtnList = flowableMapper.select_task_col_btns(map);
        //将表格列按钮更新到表格列对象中
        for(int i=0;i<tableColList.size();i++){
            Map item=tableColList.get(i);
            List<Map> colBtnList = tableColBtnList.stream()
                    .filter(o -> o.get("tableview_col_id").equals(item.get("id")))
                    .collect(Collectors.toList());
            item.put("btns", colBtnList);
        }
        re.put("tableview_columns", tableColList);
        return AjaxResult.success("suc", re);
    }

    //    @RequiresPermissions("uap:flowable:submit_form")
    @PostMapping("/submit_form")
    @ResponseBody
    public AjaxResult submit_form(@RequestBody Map<String, Object> map) {
        //从session中取当前登录人员信息
        Map userInfo = Lutils.genMap("user_name", "luyu1", "user_group", 9);
        Map form = (Map)map.get("form");
        //获取功能数据
        Map func = (Map)map.get("functionObj");
        //获取功能对应的数据表
        Map datatable = baseDBService.selectEq("v_datatable",MapUtils.G("menu_id", func.get("menu_id"))).get(0);
        String tn = datatable.get("table_name").toString();
        String msg = "未操作";
        try {
            form.put("action_type_",func.get("action_type"));
            //数据创建
            if (func.get("action_type").equals("data-create")) {
                flowableService.data_mode_create(userInfo,func, datatable, Lutils.genList(form));
            }//数据更新
            else if (func.get("action_type").equals("data-update")) {
                UserAction action = new UserAction("data-update", new Date());
                flowableService.datatable_update(userInfo, func, null, form, (Integer)map.get("id_"), datatable, "data-update", action);
            }//数据删除
            else if (func.get("action_type").equals("data-delete")) {
//                flowableService.data_mode_delete(userInfo, (List) map.get("ids"), tn);
            }//启动流程实例
            else if (func.get("action_type").equals("task-start")) {
//                flowableService.task_start(userInfo, func, datatable, Lutils.genList(form));
            }//启动流程实例
            else if (func.get("action_type").equals("task-complete")) {
//                flowableService.task_complete(userInfo,func, Lutils.genList(map.get("id_")), datatable,form);
            }
            return AjaxResult.success("操作成功");
        }
        catch(Exception e){
            System.out.println("--------------------异常------------------"+e.getMessage());
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    //    @RequiresPermissions("uap:flowable:submit_form_update")
    @PostMapping("/submit_form_update")
    @ResponseBody
    public AjaxResult submit_form_update(@RequestBody Map<String, Object> map) {
        //从session中取当前登录人员信息
        Map userInfo = Lutils.genMap("user_name", "luyu1", "user_group", 9);
        Map form = (Map)map.get("form");
        //获取功能对应的数据表
        Map datatable = baseDBService.selectEq("v_datatable",MapUtils.G("menu_id", map.get("menu_id"))).get(0);
        String tn = datatable.get("table_name").toString();
        String msg = "未操作";
        try {
//            flowableService.datatable_update(userInfo, Lutils.genMap("form_id", -1), updateFormWithIdsList, datatable, "data-update", new Date());
            return AjaxResult.success("操作成功");
        }
        catch(Exception e){
            System.out.println("--------------------异常------------------"+e.getMessage());
            e.printStackTrace();
            return AjaxResult.success(e.getMessage());
        }
    }

    /**
     * 获取表单视图数据
     * */
    //    @RequiresPermissions("uap:flowable:get_function_view")
    @PostMapping("/get_function_view")
    @ResponseBody
    public AjaxResult get_function_view(@RequestBody Map<String, Object> map) {
        Map re = new HashMap<String,Object>();
        Integer function_id = (Integer)map.get("function_id");
        Integer id_ = (Integer)map.get("id_");
        //获取功能属性
        Map func = baseDBService.selectEq("v_task_function",MapUtils.G("id", function_id)).get(0);
        re.put("functionObj", func);
        //如果是流程类
        if (func.get("action_type").toString().contains("task")) {
            if(id_!=null) { //id_不为空时，为处理任务
                //获取当前处理的数据
                Map row = baseDBService.selectEq("v_datatable"+func.get("menu_id"),MapUtils.G("id_", id_)).get(0);
                //获取当前数据对应的操作表单
                List<Map> task_form_list = baseDBService.selectEq("v_flow_usertask_form",
                        MapUtils.G("menu_id", func.get("menu_id"), "task_def_key_", row.get("task_def_key_")));
                if(task_form_list.size()>0){
                    Map task_form = task_form_list.get(0);
                    //获取表单字段
                    List formItems = baseDBService.selectEq("v_form_field",MapUtils.G("form_id", task_form.get("form_id")), Lutils.genMap("ord", "asc"));
                    re.put("formItems", formItems);
                }
                re.put("formData", row);
                return AjaxResult.success("suc", re);
            }else {//id_为空时，为发起流程
                List<Map> task_form_list = baseDBService.selectEq("v_flow_usertask_form",
                        MapUtils.G("menu_id", func.get("menu_id"),"task_def_key_", "startEvent1"));
                //获取当前数据对应的操作表单
                if(task_form_list.size()>0) {
                    Map task_form = task_form_list.get(0);
                    //获取表单字段
                    List formItems = baseDBService.selectEq("v_form_field",MapUtils.G("form_id", task_form.get("form_id")), Lutils.genMap("ord", "asc"));
                    re.put("formItems", formItems);
                }
                return AjaxResult.success("suc", re);
            }
        }
        else{ //如果是数据类
            if(id_!=null) { //id_不为空时，为修改数据
                //获取当前处理的数据
                Map row = baseDBService.selectEq("v_datatable" + func.get("menu_id"),MapUtils.G("id_", id_)).get(0);
                //获取表单字段
                List formItems = baseDBService.selectEq("v_form_field",MapUtils.G("form_id", func.get("form_id")), Lutils.genMap("ord", "asc"));
                re.put("formData", row);
                re.put("formItems", formItems);
                return AjaxResult.success("suc", re);
            }
            else{
                //获取表单字段
                List formItems = baseDBService.selectEq("v_form_field",MapUtils.G("form_id", func.get("form_id")), Lutils.genMap("ord", "asc"));
                re.put("formItems", formItems);
                return AjaxResult.success("suc", re);
            }
        }
    }

    /**
     * 获取表单视图数据
     * */
    //    @RequiresPermissions("uap:flowable:get_function")
    @PostMapping("/get_function")
    @ResponseBody
    public AjaxResult get_function(@RequestBody Map<String, Object> map) {
        List l = flowableMapper.select_function(map);
        return AjaxResult.success("suc", l);
    }


    /**
     * 获取表单视图数据
     * */
    //    @RequiresPermissions("uap:flowable:get_inst_his")
    @PostMapping("/get_inst_his")
    @ResponseBody
    public AjaxResult get_inst_his(@RequestBody Map<String, Object> map) {
        Map table = baseDBService.selectEq("v_datatable", Lutils.genMap("menu_id", map.get("menu_id"))).get(0);
        map.put("tn", table.get("table_name"));
        List<Map> l = null;
        if(table.get("type").equals("flow")){
            l=flowableMapper.get_inst_his(map);
        }
        else{
            l=flowableMapper.get_data_his(map);
        }
        //涉及到的表单
        List formItems = flowableMapper.get_related_form_field(Lutils.genMap("menu_id", map.get("menu_id"),
                "form_ids", l.stream().map(o->o.get("form_id_")).collect(Collectors.toList())));
        return AjaxResult.success("suc", Lutils.genMap("list", l, "fields", formItems));
    }

    /**
     * 获取表单视图数据
     * */
    //    @RequiresPermissions("uap:flowable:get_task_rowdata")
    @PostMapping("/get_task_rowdata")
    @ResponseBody
    public AjaxResult get_task_rowdata(@RequestBody Map<String, Object> map) {
        Map table = baseDBService.selectEq("v_datatable", Lutils.genMap("menu_id", Integer.parseInt(map.get("menu_id").toString()))).get(0);
        List<Map> l = baseDBService.selectEq(table.get("table_name").toString(), Lutils.genMap("id_", map.get("id_")));
        return AjaxResult.success("suc",  l);
    }
}
